import math
import re
from utils.ReadFile import *
# from utils.Participle import *
import datetime


def prn_obj(obj):
    """

    :param obj:
    :return:
    """
    print('-------------------------obj---------------------------------')
    _prn_obj(obj)
    pass


def prn_list(l):
    print('-------------------------list---------------------------------')
    for i in range(len(l)):
        print('~~~~~~~~~~~~~~~~~~~~~obj~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        _prn_obj(l[i])
        pass
    print('-------------------------list---------------------------------')
    pass


def _prn_obj(obj):
    print(',\n'.join(['%s:%s' % item for item in obj.__dict__.items()]))
    pass


def to_dict(obj):
    results = {}
    if isinstance(obj, list):
        results = list_to_dict(obj)
        return results
        pass
    if isinstance(obj, dict):
        results = dict_to_dict(obj)
        return results
        pass
    if not hasattr(obj, '__dict__'):
        return obj
    d = obj.__dict__
    for key in d.keys():
        if isinstance(d[key], list):
            results[key] = list_to_dict(d[key])
            continue
            pass
        if isinstance(d[key], dict):
            results[key] = dict_to_dict(d[key])
            continue
            pass
        if hasattr(d[key], '__dict__'):
            results[key] = to_dict(d[key])
            pass
        else:
            results[key] = d[key]
            pass
        pass
    return results
    pass


def list_to_dict(l):
    results = []
    for i in range(len(l)):
        results.append(to_dict(l[i]))
        pass
    return results
    pass


def dict_to_dict(d):
    results = {}
    for key in d.keys():
        results[key] = to_dict(d[key])
        pass
    return results
    pass


def get_weight(path):
    tmp = read(path, READ_LINE_LIST, ' ', 2, False)
    results = {}
    for key in tmp.keys():
        t = tmp[key]
        rs = {}
        for i in range(len(t)):
            value = i + 1
            rs[t[i]] = value
            pass
        results[key] = rs
        pass
    return results
    pass


def init_property(path):
    """
    初始化词性集合
    注 该方法为初步初始化词性集合
    后期可忽略
    :return:
    """
    p_list = os.listdir(path)
    cnt = 0
    for p in p_list:
        tmp = os.path.splitext(p)
        # 获取扩展名
        ext = tmp[1].strip('.')
        if ext == 'doc':
            continue
            pass
        # 目前只处理 pdf & docx
        text = ''
        if ext == 'pdf':
            text = read_pdf(path + '/' + p)
            pass
        if ext == 'docx':
            text = read_doc(path + '/' + p)
            pass
        if text.strip() == '':
            continue
            pass
        # seg_cut(text)
        cnt += 1
        print(cnt)
        pass
    pass


def cut_list(l, num, is_sub_len=False):
    """

    :param l:
    :param num:
    :param is_sub_len: 是否按照长度分割 or 按照分割成k个list
    True: 按照长度分割
    :return:
    """
    if is_sub_len:
        _l = num
        pass
    else:
        _l = math.ceil(len(l) / num)
        pass
    return [l[i: i + _l] for i in range(len(l)) if i % _l == 0]
    pass


def cut_training_set(training_set, length=10000):
    """
    将训练集平均切分
    :param training_set:
    :param length:
    :return:
    """
    results = {
        'sub_training_set': [],
        'tag': []
    }
    for key in training_set.keys():
        for l in cut_list(training_set[key], length, True):
            results['sub_training_set'].append(l)
            results['tag'].append(key)
            pass
        pass
    return results
    pass


def get_age_by_birthday(d1, today=datetime.datetime.now()):
    _d1 = d1
    # 格式化日期
    d1 = re.sub('[年月日号]', '', d1)
    d1 = re.sub('[/\.]', '-', d1)
    tmp = d1.split('-')
    if len(tmp) < 2:
        raise Exception('传入的日期格式有误:' + _d1)
        pass
    if len(tmp) == 2:
        tmp.append('01')
        pass
    year = int(tmp[0])
    month = tmp[1]
    day = tmp[2]
    month = int(month if len(month) != 1 else '0' + month)
    day = int(day if len(day) != 1 else '0' + day)
    year_diff = today.year - year
    if today.month < month or (today.month == month and today.day < day):
        # 还没过生日 年龄-1
        year_diff -= 1
        pass
    return year_diff
    pass


#
# def filter_file_ext(path, ext):
#     """
#     判断文件是否在对应的扩展列表中
#     使用mime类型来判断
#     :param path:
#     :param ext:
#     :return: :string 文件的实际扩展 :bool False 文件类型不符合
#     """
#     import mimetypes
#     from config.file import mime_type
#     m_type = mimetypes.guess_type(path)
#     for e in ext:
#         if m_type[0] == mime_type[e]:
#             return e
#             pass
#         pass
#     return False
#     pass


def remove_all_list(l, remove_str='', regular=False):
    if regular:
        # 全局匹配正则字符串
        p = re.compile('^' + remove_str + '$')
        return [l[i] for i in range(len(l)) if p.match(l[i]) is None]
        pass
    else:
        return [l[i] for i in range(len(l)) if l[i] != remove_str]
        pass
    pass


def remove_repeat(l):
    return list(set(l))
    pass
